package org.lanzier.common.service.impl;

import java.util.List;
import java.util.Map;

import org.lanzier.common.exception.LanzierException;
import org.lanzier.common.form.PaginForm;
import org.lanzier.common.form.RequestDataForm;
import org.lanzier.common.form.ResponseDataForm;
import org.lanzier.common.sqlparse.SqlResultForm;
import org.lanzier.common.utils.Environment;
import org.lanzier.common.utils.MapUtils;
import org.lanzier.common.utils.XmlUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author lansb query Service
 */
@Service("queryService")
public class QueryService extends AbstractService {
	public ResponseDataForm service(RequestDataForm requestDataForm) throws Exception {
		// 实现如下:
		ResponseDataForm rdf = new ResponseDataForm();
		Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
		Map<String, String> simpleRequestMap = requestDataForm.getSimpleRequestMap();
		int numPerPage = MapUtils.getInt(simpleRequestMap, Environment.CTRL_NUMPERPAGE, Environment.DEFAULT_NUMPERPAGE);
		String execSql = MapUtils.getString(urlSqlMap, "EXEC_SQL");
		logger.debug("\n\r\t 待解析的xml：" + execSql);
		if ("".equals(execSql)) { 
			throw new LanzierException("exec sql is null");
		}
		NodeList sqlNodes = XmlUtils.getNoteListByString(execSql);
		Element element = null;
		for (int i = 0; i < sqlNodes.getLength(); i++) {
			Node child = sqlNodes.item(i);
			if (child.getNodeType() != Node.ELEMENT_NODE)
				continue;
			element = (Element) child;
			PaginForm paginForm = new PaginForm();
			if("true".equals(element.getAttribute("paginType"))) {//dynamic动态分页,normal普通分页,none不分页，一次查出所有数据
				simpleRequestMap.put(Environment.CTRL_QUERYCOUNT, "havet");//新增查询总数条件,值为随意
				SqlResultForm rsf = sqlParse.parseNode(element, simpleRequestMap);
				simpleRequestMap.remove(Environment.CTRL_QUERYCOUNT);//移除查询总数条件
				int count = Integer.parseInt(jdbcDao.queryForString(rsf.getParsedSql(), rsf.getValueList().toArray()));//获取总数
				paginForm.setTotalCount(count);
			} 
			int pageNum = MapUtils.getInt(simpleRequestMap, Environment.CTRL_PAGENUM, Environment.DEFAULT_PAGENUM);
			int startNum = numPerPage*(pageNum-1);
			simpleRequestMap.put(Environment.CTRL_PAGESTART, String.valueOf(startNum));
			simpleRequestMap.put(Environment.CTRL_NUMPERPAGE, String.valueOf(numPerPage));
			SqlResultForm rsf = sqlParse.parseNode(element, simpleRequestMap);
			List rsList = jdbcDao.queryForList(rsf.getParsedSql(), rsf.getValueList().toArray());//获取总数
			paginForm.setPageNum(pageNum);
			paginForm.setDataList(rsList);
			paginForm.setNumPerPage(numPerPage);
			paginForm.setStartNum(startNum);
			paginForm.setPageNumShown(MapUtils.getInt(simpleRequestMap, Environment.CTRL_PAGENUMSHOWN, Environment.DEFAULT_PAGENUMSHOWN));
			rdf.setPaginForm(paginForm); 
		}
		return rdf; 
		
	}
}
